package edu.colorado.karl.intelsched;

/**
 * This class is an automatically resizing String array
 * @author Michael Knudson
 * @version 11/5/2007
 */
public class StringArray {
	private int capacity;
	private String[] array;
	private int used;
	
	/**
	 * Creates a new StringArray with a default capacity of seven.
	 */
	public StringArray() {
		capacity = 7;
		array = new String[capacity];
		used = 0;
	}
	
	/**
	 * Adds a String to the array.  If the array is full, it doubles the current capacity and then adds the String.
	 * @param s The String to be added.
	 */
	public void add(String s) {
		if(used >= capacity)
			resize();
		
		array[used++] = s;
	}

	/**
	 * Retrieves the String from the array at the given index.
	 * @param index The array index to examine.
	 * @exception ArrayIndexOutOfBoundsException if the given index is invalid.
	 * @return The String found at the given index.
	 */
	public String get(int index) {
		if(index >= used || index < 0)
			throw new ArrayIndexOutOfBoundsException("Invalid index: " + index + " (max index: " + (used-1) + ")");
		return array[index];
	}
	
	/**
	 * Prints the entire array to System.out, one String per line.
	 */
	public void printContents() {
		for(int i=0; i<used; ++i) {
			System.out.println(array[i]);
		}
	}
	
	private void resize() {
		capacity = capacity * 2;
		String[] temp = array;
		array = new String[capacity];
		
		for (int i = 0; i < temp.length; i++) {
			array[i] = temp[i];
		}
	}
	
	/**
	 * Returns the size of the StringArray.
	 * @return Current number of strings in the array.
	 */
	public int size() {
		return used;
	}
}
